/**
 * formdata 补丁, 给不支持formdata上传blob的android机打补丁
 * @constructor
 */
function FormDataShim() {
    console.warn('using formdata shim');
    var o = this,
        parts = [],
        boundary = Array(21).join('-') + (+new Date() * (1e16 * Math.random())).toString(36),
        oldSend = XMLHttpRequest.prototype.send;
    this.append = function (name, value, filename) {
        parts.push('--' + boundary + '\r\nContent-Disposition: form-data; name="' + name + '"');
        if (value instanceof Blob) {
            parts.push('; filename="' + (filename || 'blob') + '"\r\nContent-Type: ' + value.type + '\r\n\r\n');
            parts.push(value);
        } else {
            parts.push('\r\n\r\n' + value);
        }
        parts.push('\r\n');
    };
    // Override XHR send()
    XMLHttpRequest.prototype.send = function (val) {
        var fr,
            data,
            oXHR = this;
        if (val === o) {
            // Append the final boundary string
            parts.push('--' + boundary + '--\r\n');
            // Create the blob
            data = getBlob(parts);
            // Set up and read the blob into an array to be sent
            fr = new FileReader();
            fr.onload = function () {
                oldSend.call(oXHR, fr.result);
            };
            fr.onerror = function (err) {
                throw err;
            };
            fr.readAsArrayBuffer(data);
            // Set the multipart content type and boudary
            this.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
            XMLHttpRequest.prototype.send = oldSend;
        } else {
            oldSend.call(this, val);
        }
    };
}
;
;
(function ($) {
    var __Upload = {
        op: {
            button: "upload",
            uploadUrl: "",
            filechooser: document.getElementById("choose"),
            maxTotal: 5,
            maxUpTotal: 2,
            canvas: document.createElement("canvas"), //    用于压缩图片的canvas
            ctx: null, //    用于压缩图片的canvas
            tCanvas: document.createElement("canvas"), //    瓦片canvas
            tctx: null,
            maxsize: 3000 * 1024,
            li_length: ''
        },
        canvas: function (canvasa, canvasb) {
            __Upload.op.canvas = document.createElement(canvasa); //    用于压缩图片的canvas
            __Upload.op.ctx = __Upload.op.canvas.getContext('2d'); //    用于压缩图片的canvas
            __Upload.op.tCanvas = document.createElement(canvasb); //    瓦片canvas
            __Upload.op.tctx = __Upload.op.tCanvas.getContext("2d");
        },
        filechoose: function (ths) {
            console.log(ths.files.length + 5, '5555');
            //    var c = ths.files.length+=ths.files.length+1
            //     console.log(c)

            console.log(ths.files.length = ths.files.length + 1)
            // $('#choose').change(function(){

            //     console.log( li_length,'5525252')
            // })

            // $(".img-list").on("resize", "li", function () {
            //     console.log($(".img-list li"),'这是')
            // })
            //获取元素的长度

            $('body').on('change', '#choose', function () {
                var li_length = $('.img-list li').length
                // __Upload.op.li_length = li_length

                nums(li_length)
            })

            //    nums()
            function nums(li_length) {
                console.log(li_length,'这是多少')
                if (!ths.files.length)
                return;
            var files = Array.prototype.slice.call(ths.files);
            if ($(".__upimg__").length >= __Upload.op.maxTotal) {
                alert("最多可上传" + __Upload.op.maxTotal + "张图片");
                return;
            }
            if (li_length > __Upload.op.maxTotal) {
                alert("最多同时只可上传" + __Upload.op.maxTotal + "张图片");
                $('.filebox').hide()
                $("#picUpload").hide()
                $(".img-list").children('li').remove()
                return;
            }
            }

            $('#uploadSwitch').click(function(){
               console.log( $('.img-list li').length>0)
                if($('.img-list li').length==0){
                    $('.filebox').show()
                    $("#picUpload").show()
                    // $(".img-list").show()
                }
            })

            var files = Array.prototype.slice.call(ths.files);
            // if (!ths.files.length)
            //     return;
       
            // console.log(files, '6666')
            // if ($(".__upimg__").length >= __Upload.op.maxTotal) {
            //     alert("最多可上传" + __Upload.op.maxTotal + "张图片");
            //     return;
            // }
            // if (__Upload.op.li_length > __Upload.op.maxTotal) {
            //     alert("最多同时只可上传" + __Upload.op.maxTotal + "张图片");
            //     $('.filebox').hide()
            //     return;
            // }

            files.forEach(function (file, i) {
                if (!/\/(?:jpeg|png|gif)/i.test(file.type))
                    return;
                var reader = new FileReader();
                var li = document.createElement("li");
                var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
                if (file.size > __Upload.op.maxsize) {
                    li.innerHTML = '<div class="clase-del-img" data-imgid=""></div><div class="progress" ><span style="width:100%">图片需小于1M</span></div><div class="size">' + size + '</div>';
                } else {
                    li.innerHTML = '<div class="clase-del-img" data-imgid=""></div><div class="progress"><span></span></div><div class="size">' + size + '</div>';
                }
                // 获取图片大小
                // var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";

                $(".img-list").append($(li));






                reader.onload = function () {
                    var result = this.result;
                    var img = new Image();
                    img.src = result;
                    console.log($(li), '22222')
                    $(li).css("background-image", "url(" + result + ")");
                    //如果图片大小小于100kb，则直接上传
                    console.log('压缩前：' + file.size);
                    console.log('压缩前：' + result.length);
                    if (result.length <= __Upload.op.maxsize) {
                        img = null;
                        __Upload.upload(result, file.type, $(li));
                        return;
                    }
                    //图片加载完毕之后进行压缩，然后上传


                };
                reader.readAsDataURL(file);
            })
        },
        filechooseToDo: function (ths, dom, err, fun) {

            if (!ths.files.length)
                return;
            var files = Array.prototype.slice.call(ths.files);

            if (files.length > __Upload.op.maxTotal) {
                alert("最多可上传" + __Upload.op.maxTotal + "张图片");
                return;
            }

            files.forEach(function (file, i) {
                if (!/\/(?:jpeg|png|gif)/i.test(file.type))
                    return;
                var reader = new FileReader();
                //var li = document.createElement("li");
                var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";
                if (file.size > __Upload.op.maxsize) {
                    err("图片需小于1M");
                    //li.innerHTML = '<div class="clase-del-img" data-imgid="">x</div><div class="progress" ><span style="width:100%">图片需小于1M</span></div><div class="size">' + size + '</div>';
                } else {
                    //li.innerHTML = '<div class="clase-del-img" data-imgid="">x</div><div class="progress"><span></span></div><div class="size">' + size + '</div>';
                }
                // 获取图片大小
                // var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB";

                //$(".img-list").append($(li));
                reader.onload = function () {
                    var result = this.result;
                    var img = new Image();
                    img.src = result;
                    //$(li).css("background-image", "url(" + result + ")");
                    //如果图片大小小于100kb，则直接上传
                    console.log('压缩前：' + file.size);
                    if (result.length <= __Upload.op.maxsize) {
                        img = null;
                        __Upload.supload(result, file.type, dom, fun);
                        return;
                    }
                    //图片加载完毕之后进行压缩，然后上传


                };
                reader.readAsDataURL(file);
            })
        },
        //    使用__Upload.op.tCanvas对大图片进行压缩
        compress: function (img) {
            var initSize = img.src.length;
            var width = img.width;
            var height = img.height;
            //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
            var ratio;
            if ((ratio = width * height / 4000000) > 1) {
                ratio = Math.sqrt(ratio);
                width /= ratio;
                height /= ratio;
            } else {
                ratio = 1;
            }
            __Upload.op.tCanvas.width = width;
            __Upload.op.tCanvas.height = height;
            //        铺底色
            __Upload.op.ctx.fillStyle = "#fff";
            __Upload.op.ctx.fillRect(0, 0, __Upload.op.tCanvas.width, __Upload.op.tCanvas.height);
            //如果图片像素大于100万则使用瓦片绘制
            var count;
            if ((count = width * height / 1000000) > 1) {
                count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
                //            计算每块瓦片的宽和高
                var nw = ~~(width / count);
                var nh = ~~(height / count);
                __Upload.op.tCanvas.width = nw;
                __Upload.op.tCanvas.height = nh;
                for (var i = 0; i < count; i++) {
                    for (var j = 0; j < count; j++) {
                        __Upload.op.tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                        ctx.drawImage(__Upload.op.tCanvas, i * nw, j * nh, nw, nh);
                    }
                }
            } else {
                __Upload.op.ctx.drawImage(img, 0, 0, width, height);
            }
            //进行最小压缩
            var ndata = __Upload.op.tCanvas.toDataURL('image/jpeg', 0.8);
            console.log('压缩前：' + initSize);
            console.log('压缩后：' + ndata.length);
            console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
            __Upload.op.tCanvas.width = __Upload.op.tCanvas.height = __Upload.op.tCanvas.width = __Upload.op.tCanvas.height = 0;
            return ndata;
        },
        //    图片上传，将base64的图片转成二进制对象，塞进formdata上传
        upload: function (basestr, type, $li) {
            var text = window.atob(basestr.split(",")[1]);
            var buffer = new Uint8Array(text.length);
            var pecent = 0, loop = null;
            for (var i = 0; i < text.length; i++) {
                buffer[i] = text.charCodeAt(i);
            }
            var blob = __Upload.getBlob([buffer], type);
            var xhr = new XMLHttpRequest();
            var formdata = __Upload.getFormData();

            formdata.append('imagefile', blob);
            formdata.append('timestamp', __SiteAppCommon__.timestamp);
            formdata.append('token', __SiteAppCommon__.token);
            xhr.open('post', __Upload.op.uploadUrl);
            xhr.onreadystatechange = function () {


                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(xhr.responseText, '66666');
                    console.log('uping');
                    var imagedata = jQuery.parseJSON(xhr.responseText);

                    clearInterval(loop);
                    //当收到该消息时上传完毕  //这是上传时候的进度条效果 请求成功就会显示上传进度条效果
                    $li.find(".progress span").animate({ 'width': "100%" }, pecent < 95 ? 200 : 0, function () {
                        $(this).html('imagedata.message');
                    });
                    // --------------------------
                    $li.find(".clase-del-img").attr("data-imgid", imagedata.name);
                    if (!imagedata.src)
                        return;
                    $(".pic-list").append('<input name="imgs[' + imagedata.imgid + ']" type="hidden" class="__upimg__ ' + imagedata.name + '" value="' + imagedata.src + '"><input name="thumbnails[' + imagedata.imgid + ']" type="hidden" class="__upthumbnailimg__  ' + imagedata.name + '" value="' + imagedata.thumbnailsrc + '"><input name="imgid[' + imagedata.imgid + ']" type="hidden" class="__upimgid__  ' + imagedata.name + '" value="' + imagedata.imgid + '">');
                    //$(".pic-list").append('<a href="' + imagedata.path + '">' + imagedata.name + '（' + imagedata.size + '）<img src="' + imagedata.path + '" /></a>');
                    if ($(".__upimg__").length == __Upload.op.maxTotal) {
                        $("#" + __Upload.op.button).hide();
                    }

                }
            };
            //数据发送进度，前50%展示该进度
            xhr.upload.addEventListener('progress', function (e) {
                if (loop)
                    return;
                pecent = ~~(100 * e.loaded / e.total) / 2;
                $li.find(".progress span").css('width', pecent + "%");
                if (pecent == 50) {
                    mockProgress();
                }
            }, false);
            //数据后50%用模拟进度
            function mockProgress() {
                if (loop)
                    return;
                loop = setInterval(function () {
                    pecent++;
                    $li.find(".progress span").css('width', pecent + "%");
                    if (pecent == 99) {
                        clearInterval(loop);
                    }
                }, 100)
            }
            //  console.log(formdata,'formadata')
            xhr.send(formdata);
        },
        supload: function (basestr, type, $li, call) {
            var text = window.atob(basestr.split(",")[1]);
            var buffer = new Uint8Array(text.length);
            var pecent = 0, loop = null;
            for (var i = 0; i < text.length; i++) {
                buffer[i] = text.charCodeAt(i);
            }
            var blob = __Upload.getBlob([buffer], type);
            var xhr = new XMLHttpRequest();
            var formdata = __Upload.getFormData();
            var imagedata;
            formdata.append('imagefile', blob);
            formdata.append('timestamp', __SiteAppCommon__.timestamp);
            formdata.append('token', __SiteAppCommon__.token);
            xhr.open('post', __Upload.op.uploadUrl);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //console.log(xhr.responseText);
                    imagedata = jQuery.parseJSON(xhr.responseText);
                    call(imagedata);
                    //                    //clearInterval(loop);
                    //                    return imagedata; 
                }
            };
            //数据发送进度，前50%展示该进度
            xhr.upload.addEventListener('progress', function (e) {
                if (loop)
                    return;
                pecent = ~~(100 * e.loaded / e.total) / 2;
                $li.find(".progress span").css('width', pecent + "%");
                if (pecent == 50) {
                    mockProgress();
                }
            }, false);
            //数据后50%用模拟进度
            function mockProgress() {
                if (loop)
                    return;
                loop = setInterval(function () {
                    pecent++;
                    $li.find(".progress span").css('width', pecent + "%");
                    if (pecent == 100) {
                        $li.find(".progress span").html("上传成功");
                        clearInterval(loop);
                    }
                }, 100)
            }
            // console.log(formdata,'formadata')
            xhr.send(formdata);

        },
        /**
         * 获取blob对象的兼容性写法
         * @param buffer
         * @param format
         * @returns 
         */
        getBlob: function (buffer, format) {
            try {
                return new Blob(buffer, { type: format });
            } catch (e) {
                var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
                buffer.forEach(function (buf) {
                    bb.append(buf);
                });
                return bb.getBlob(format);
            }
        },
        /**
         * 获取formdata
         */
        getFormData: function () {
            var isNeedShim = ~navigator.userAgent.indexOf('Android')
                && ~navigator.vendor.indexOf('Google')
                && !~navigator.userAgent.indexOf('Chrome')
                && navigator.userAgent.match(/AppleWebKit\/(\d+)/).pop() <= 534;
            return isNeedShim ? new FormDataShim() : new FormData()
        },

    }
        ;
    $(document).ready(function () {
        $(".img-list").delegate(".clase-del-img", "click", function () {
            // console.log("updel");
            var thisid = $(this).data("imgid");
            var index = $(".clase-del-img").index(this);

            $(".img-list li").eq(index).remove();
            $("." + thisid).remove();
            if ($(".__upimg__").length < __Upload.op.maxTotal) {
                $("#" + __Upload.op.button).show();
            }
            var li_length = $('.img-list li').length + 1
            console.log(li_length, '8888')
            if (li_length < __Upload.op.maxTotal) {
                $('.filebox').show()

            }
        });
    })



    window.__Upload = $.__Upload = $.__Upload = __Upload;
})(this.__Upload || this.jQuery && (this.__Upload = jQuery)); 